require("hwOutMsg")
require("tool")
require("misc")
require("lbsLoc")

module(..., package.seeall)

local lng_value = "0"
local lat_value = "0"
local beat = 0
local function devNotInList(list, dev_name)
    for i, v in ipairs(list) do
        if list[i].device_id == dev_name then return false end
    end

    return true
end

-- 获取网关的经纬度
local function getLocCb(result, lat, lng, addr, time, locType)
    log.info("testLbsLoc.getLocCb", result, lat, lng)
    -- 获取经纬度成功
    if result == 0 then
        -- log.info("服务器返回的时间", time:toHex())
        -- log.info("定位类型，基站定位成功返回0", locType)
        lat_value = tostring(lat)
        lng_value = tostring(lng)
        return true
        -- 失败
    else
        return false
    end
end

-- 设备初次启动
local function onceStart()
    if hwIotda.isReady() then
        sys.taskInit(function()
            ril.regUrc("+NITZ", function()
                log.info("cell.timeSync")
                bTimeSyned = true
            end)

            sys.wait(1000)
            lbsLoc.request(getLocCb)
            -- local t = misc.getClock()
            -- misc.getTemperature(getTemperatureCb)

            local clk = os.date("*t", os.time()) -- 获取UTC时间的table
            local timeStr = string.format("%02d-%02d-%02d %02d:%02d:%02d",
                                          clk.year, clk.month, clk.day,
                                          clk.hour, clk.min, clk.sec) -- 时间戳
            log.info("HW time", timeStr)

            sys.wait(1000)
            -- local num, on_num = ui_index.returnOnlineNum()
            local re = {}
            re["services"] = {{}}
            re["services"][1]["service_id"] = "base"
            re["services"][1]["properties"] = {}
            if lat_value ~= "0" or lng_value ~= "0" then
                re["services"][1]["properties"]["lat"] = tonumber(lat_value)
                re["services"][1]["properties"]["lon"] = tonumber(lng_value)
            end
            re["services"][1]["properties"]["fwVersion"] = _G.VERSION
            re["services"][1]["properties"]["supplier"] = "LINKTA"
            re["services"][1]["properties"]["model"] = "LTG-03"
            re["services"][1]["properties"]["iccid"] = tostring(sim.getIccid())
            re["services"][1]["properties"]["rssi"] = net.getRssi()
            re["services"][1]["properties"]["reportTime"] = timeStr
            re["services"][1]["properties"]["pass"] = nvm.get("PASSWORD")

            hwOutMsg.hwInstertMsg("$oc/devices/" .. config.HW_DEV_PRODUCTID ..
                                      "_GWRD_" .. misc.getImei() ..
                                      "/sys/properties/report", re)
            -- mqttOutMsg.mqttInsertMsg(config.MQTT_TOPIC2, re)
        end)
    end
end

-- 华为云子设备数据上传
function dataPost(data_buf, type)
    if hwIotda.isReady() then
        beat = tool.miscTime()
        sys.taskInit(function()
            local re = {}
            re["devices"] = {}

            for i, val in ipairs(data_buf) do
                local temp = {}
                -- log.info("POST DATA", val.addr, val.data[1])
                if val.addr ~= "" and val.data[1] ~= -9999 and val.data[1] ~=
                    -8888 and val.data[1] ~= nil then
                    temp["device_id"] = nvm.get("DEV_SUB_PRODUCT") .. "_" ..
                                            string.sub(misc.getImei(), -6, -1) ..
                                            "_" .. nvm.get("DEV_SUB_TAG") ..
                                            val.addr
                    temp["services"] = {{}}
                    temp["services"][1]["service_id"] = "sensor"
                    temp["services"][1]["properties"] = {}

                    -- 电表数据发送
                    if nvm.get("DEV_SUB_TAG") == "E" and #val.data == 7 then
                        temp["services"][1]["properties"]["value"] = val.data[7]
                        temp["services"][1]["properties"]["voltage_list"] = {
                            val.data[1], val.data[2], val.data[3]
                        }
                        temp["services"][1]["properties"]["current_list"] = {
                            val.data[4], val.data[5], val.data[6]
                        }
                        table.insert(re["devices"], temp)
                    elseif nvm.get("DEV_SUB_TAG") == "T" or
                        nvm.get("DEV_SUB_TAG") == "F" or nvm.get("DEV_SUB_TAG") ==
                        "P" or nvm.get("DEV_SUB_TAG") == "W" or
                        nvm.get("DEV_SUB_TAG") == "L" then
                        if #val.data == 1 then
                            if type == "normal" then
                                temp["services"][1]["properties"]["value"] =
                                    val.data[1]
                            elseif type == "off" then
                                temp["services"][1]["properties"]["powerOffValue"] =
                                    val.data[1]
                            elseif type == "on" then
                                temp["services"][1]["properties"]["powerOnValue"] =
                                    val.data[1]
                            elseif type == "button" then
                                temp["services"][1]["properties"]["handValue"] =
                                    val.data[1]
                            elseif type == "zero" then
                                temp["services"][1]["properties"]["zeroValue"] =
                                    val.data[1]
                            end
                        elseif #val.data == 2 then
                            -- 奶牛场早晚班流量计数据发送
                            temp["services"][1]["properties"]["value"] =
                                val.data[1]
                            temp["services"][1]["properties"]["singleValue"] =
                                val.data[2]
                        end
                        table.insert(re["devices"], temp)
                    elseif nvm.get("DEV_SUB_TAG") == "G" and #val.data == 3 then
                        -- 蒸汽表数据发送，蒸汽量、温度、压力
                        temp["services"][1]["properties"]["value"] = val.data[1]
                        temp["services"][1]["properties"]["temp"] = val.data[2]
                        temp["services"][1]["properties"]["press"] = val.data[3]
                        table.insert(re["devices"], temp)
                    end
                end

            end

            -- 有数据才发送
            if #re["devices"] > 0 then
                hwOutMsg.hwInstertMsg(
                    "$oc/devices/" .. config.HW_DEV_PRODUCTID .. "_GWRD_" ..
                        misc.getImei() ..
                        "/sys/gateway/sub_devices/properties/report", re)
            end
        end)
    end
end

-- 子设备上线
function subsetLogin(id)
    log.info("HW LOGIN", id)

    local data = {}
    data["services"] = {{}}
    data["services"][1]["service_id"] = "$sub_device_manager"
    data["services"][1]["event_type"] = "sub_device_update_status"
    data["services"][1]["paras"] = {}
    data["services"][1]["paras"]["device_statuses"] = {}

    for i, re in ipairs(id) do
        local temp = {}
        temp["device_id"] = nvm.get("DEV_SUB_PRODUCT") .. "_" .. re
        temp["status"] = "ONLINE"
        table.insert(data["services"][1]["paras"]["device_statuses"], temp)
    end

    hwOutMsg.hwInstertMsg(
        "$oc/devices/" .. config.HW_DEV_PRODUCTID .. "_GWRD_" .. misc.getImei() ..
            "/sys/events/up", data)
end

-- 子设备下线
function subsetLogout(id)
    log.info("HW LOGOut", id)

    local data = {}
    data["services"] = {{}}
    data["services"][1]["service_id"] = "$sub_device_manager"
    data["services"][1]["event_type"] = "sub_device_update_status"
    data["services"][1]["paras"] = {}
    data["services"][1]["paras"]["device_statuses"] = {}

    for i, re in ipairs(id) do
        local temp = {}
        temp["device_id"] = nvm.get("DEV_SUB_PRODUCT") .. "_" .. re
        temp["status"] = "OFFLINE"
        table.insert(data["services"][1]["paras"]["device_statuses"], temp)
    end

    hwOutMsg.hwInstertMsg(
        "$oc/devices/" .. config.HW_DEV_PRODUCTID .. "_GWRD_" .. misc.getImei() ..
            "/sys/events/up", data)
end

-- 更新拓扑关系
function updateTopo()
    local topic = "$oc/devices/" .. config.HW_DEV_PRODUCTID .. "_GWRD_" ..
                      misc.getImei() .. "/sys/events/up"
    local re = {}
    re["services"] = {{}}
    re["services"][1]["service_id"] = "$sub_device_manager"
    re["services"][1]["event_type"] = "sub_device_sync_request"
    re["services"][1]["paras"] = {}
    -- re["services"][1]["paras"]["version"] = 1
    hwOutMsg.hwInstertMsg(topic, re)
    log.info("HW UPDATE TOPO")
end

-- 新增子设备
function subDevAdd(id)
    local data = {}
    data["services"] = {{}}
    data["services"][1]["service_id"] = "$sub_device_manager"
    data["services"][1]["event_type"] = "add_sub_device_request"
    data["services"][1]["paras"] = {}
    data["services"][1]["paras"]["devices"] = {{}}
    data["services"][1]["paras"]["devices"][1]["name"] = id
    data["services"][1]["paras"]["devices"][1]["node_id"] = id
    data["services"][1]["paras"]["devices"][1]["product_id"] = nvm.get(
                                                                   "DEV_SUB_PRODUCT")

    hwOutMsg.hwInstertMsg(
        "$oc/devices/" .. config.HW_DEV_PRODUCTID .. "_GWRD_" .. misc.getImei() ..
            "/sys/events/up", data)
end

-- 删除子设备
function subDevDelet(id)
    local data = {}
    data["services"] = {{}}
    data["services"][1]["service_id"] = "$sub_device_manager"
    data["services"][1]["event_type"] = "delete_sub_device_request"
    data["services"][1]["paras"] = {}
    data["services"][1]["paras"]["devices"] = {{}}
    data["services"][1]["paras"]["devices"][1] = id

    hwOutMsg.hwInstertMsg(
        "$oc/devices/" .. config.HW_DEV_PRODUCTID .. "_GWRD_" .. misc.getImei() ..
            "/sys/events/up", data)
end

-- 处理华为云命令
function hwCMD(topic, payload)
    sys.taskInit(function()
        local res = tool.Split(topic, "/")
        local jsondata, json_result, errinfo = json.decode(payload)
        if #res == 6 and res[5] == "commands" then
            if json_result == true then
                -- 重启命令
                if jsondata["command_name"] == "CMD_REBOOT" then
                    local re = {["result_code"] = 0, ["paras"] = {}}
                    hwOutMsg.hwInstertMsg("$oc/devices/" ..
                                              config.HW_DEV_PRODUCTID ..
                                              "_GWRD_" .. misc.getImei() ..
                                              "/sys/commands/response/" ..
                                              res[6], re)
                    sys.wait(2000)
                    sys.restart("HW CMD REBOOT")
                elseif jsondata["command_name"] == "CMD_HEX" then
                    deviceConfig.hwMqttSend(jsondata["paras"]["data"], topic)
                end

            end
        end

    end)
end

-- 启动定时上传心跳包任务
sys.taskInit(function()
    local result, data = sys.waitUntil("HW_MQTT_READY", 300000)
    if result then
        sys.wait(6000)
        onceStart()
        while true do
            sys.wait(300000)
            if tool.miscTime() - beat > 300 then onceStart() end
        end
    end
end)
